const { DataSystemDictDataModel } = require("../models/sys_dict_data");
const { DataSystemPostModel } = require("../models/sys_post");
const { fail, CODE, success } = require("../utils/utils");
const xlsx = require("node-xlsx");

class SystemPostController {
  /**
   * @description 添加岗位
   * @param {String} post_name
   * @param {String} post_code
   * @param {Number} post_sort
   * @param {Number} status
   * @param {String} remark
   * @param {String} op_user_id
   */
  static async sysPostAdd (ctx, next) {
    const {
      post_name,
      post_code,
      post_sort = 0,
      status = "1",
      remark,
    } = ctx.request.body;
    try {
      const { user_id: op_user_id } = ctx.state.user;
      if (!post_name) {
        return (ctx.body = fail([], `请输入岗位`, CODE.BUSINESS_ERROR));
      }
      const sysPostInfo = await DataSystemPostModel.findBySystemPostName({
        post_name,
      });
      if (sysPostInfo) {
        return (ctx.body = fail([], `岗位已存在`, CODE.BUSINESS_ERROR));
      }
      const sysPostCodeInfo = await DataSystemPostModel.findBySystemPostCode({
        post_code,
      });
      if (sysPostCodeInfo) {
        return (ctx.body = fail([], `岗位编码已存在`, CODE.BUSINESS_ERROR));
      }
      const result = await DataSystemPostModel.create({
        post_name,
        post_code,
        post_sort,
        status,
        remark,
        op_user_id,
      });
      return (ctx.body = success([], `新增岗位成功`, CODE.SUCCESS));
    } catch (error) {
      return (ctx.body = fail([], error.message, CODE.BUSINESS_ERROR));
    }
  }
  /**
   * @description 更新岗位
   * @param {Number} post_id
   * @param {String} post_name
   * @param {String} post_code
   * @param {Number} post_sort
   * @param {Number} status
   * @param {String} remark
   * @param {String} op_user_id
   */
  static async sysPostUpd (ctx, next) {
    const { post_id, post_name, post_code, post_sort, status, remark } =
      ctx.request.body;
    try {
      const { user_id: op_user_id } = ctx.state.user;
      if (!post_id) {
        return (ctx.body = fail([], `请输入必填项`, CODE.BUSINESS_ERROR));
      }
      const sysPostInfo = await DataSystemPostModel.findBySystemPostNameNeId({
        post_name,
        post_id,
      });
      if (sysPostInfo) {
        return (ctx.body = fail([], `岗位已存在`, CODE.BUSINESS_ERROR));
      }
      const sysPostCodeInfo = await DataSystemPostModel.findBySystemPostCodeId({
        post_code,
        post_id,
      });
      if (sysPostCodeInfo) {
        return (ctx.body = fail([], `岗位编码已存在`, CODE.BUSINESS_ERROR));
      }
      await DataSystemPostModel.update({
        post_name,
        post_code,
        post_sort,
        status,
        remark,
        op_user_id,
        post_id,
      });
      return (ctx.body = success([], `岗位更新成功`, CODE.SUCCESS));
    } catch (error) {
      return (ctx.body = fail([], error.message, CODE.BUSINESS_ERROR));
    }
  }
  /**
   * @description 删除岗位
   * @param {Number} post_id
   */
  static async sysPostDel (ctx, next) {
    const { post_id } = ctx.request.body;
    try {
      const { user_id: op_user_id } = ctx.state.user;
      if (!post_id) {
        return (ctx.body = fail([], `post_id 获取失败`, CODE.BUSINESS_ERROR));
      }
      await DataSystemPostModel.delete({ op_user_id, post_id });
      return (ctx.body = success([], `岗位删除成功`, CODE.SUCCESS));
    } catch (error) {
      return (ctx.body = fail([], error.message, CODE.BUSINESS_ERROR));
    }
  }

  /**
   * @description 批量删除岗位
   * @param {Number} ids
   */
  static async sysPostDelByIds (ctx, next) {
    const { ids } = ctx.request.body;
    try {
      const { user_id: op_user_id } = ctx.state.user;
      if (!ids || !Array.isArray(ids) || ids.length === 0) {
        return (ctx.body = fail([], `删除失败`, CODE.BUSINESS_ERROR));
      }
      await DataSystemPostModel.deleteByIds({ op_user_id, ids });
      return (ctx.body = success([], `岗位批量删除成功`, CODE.SUCCESS));
    } catch (error) {
      return (ctx.body = fail([], error.message, CODE.BUSINESS_ERROR));
    }
  }

  /**
   * @description 岗位分页列表
   * @param {String} post_name
   * @param {String} post_code
   * @param {String} status
   * @param {String} limit
   * @param {String} size
   */
  static async sysPostList (ctx, next) {
    try {
      const { page_num, page_size, post_name, post_code, status } =
        ctx.request.query;
      const { data_scope = "" } = ctx.state;
      let limit = Number(page_num) || 1;
      let size = Number(page_size) || 10;
      const { result, count } = await DataSystemPostModel.list({
        limit,
        size,
        post_name,
        post_code,
        status,
        data_scope,
      });
      return (ctx.body = success(
        { result, total: count[0].count },
        `获取岗位数据成功`,
        CODE.SUCCESS
      ));
    } catch (error) {
      return (ctx.body = fail([], error.message, CODE.BUSINESS_ERROR));
    }
  }
  /**
   * @description 岗位所有列表
   * @param {String} name
   * @param {String} status
   */
  static async sysAllPostList (ctx, next) {
    const { data_scope = "" } = ctx.state;
    try {
      const { result } = await DataSystemPostModel.all({ data_scope });
      return (ctx.body = success({ result }, `获取岗位数据成功`, CODE.SUCCESS));
    } catch (error) {
      return (ctx.body = fail([], error.message, CODE.BUSINESS_ERROR));
    }
  }
  /**
   * @description 通过岗位id获取数据
   * @param {Number} post_id
   */
  static async sysPostById (ctx, next) {
    const { post_id } = ctx.request.query;
    try {
      if (!post_id) {
        return (ctx.body = fail([], `post_id 获取失败`, CODE.BUSINESS_ERROR));
      }
      const result = await DataSystemPostModel.findBySystemPostId({
        post_id: Number(post_id),
      });
      return (ctx.body = success(result, `获取岗位数据成功`, CODE.SUCCESS));
    } catch (error) {
      return (ctx.body = fail([], error.message, CODE.BUSINESS_ERROR));
    }
  }
  /**
   * @description 导出数据
   */
  static async sysPostExport (ctx, next) {
    try {
      const { data_scope = "" } = ctx.state;
      const { post_name, post_code, status } = ctx.request.body;
      const { result } = await DataSystemPostModel.findList({
        post_name,
        post_code,
        status,
        data_scope,
      });
      const sys_normal_disable_result =
        await DataSystemDictDataModel.findBySystemdDictType({
          dict_type: "sys_normal_disable",
        });
      let data = result.map((item) => {
        let current_staus = sys_normal_disable_result.find(
          (snd) => snd.dict_value === item.status
        );
        item.status = current_staus ? current_staus.dict_label : item.status;
        return item;
      });
      const excelData = [
        [
          "岗位编号",
          "岗位名称",
          "岗位编码",
          "岗位排序",
          "状态",
          "备注",
          "创建时间",
        ],
        ...data.map((item) => [
          item.post_id,
          item.post_name,
          item.post_code,
          item.post_sort,
          item.status,
          item.remark,
          item.create_time,
        ]),
      ];
      const buffer = xlsx.build([{ name: "Sheet1", data: excelData }]);

      // 设置返回的http header信息，告诉浏览器该文件是一个excel文件
      ctx.set(
        "Content-Type",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      );
      ctx.set(
        "Content-Disposition",
        "attachment; filename=" + encodeURIComponent("岗位数据.xlsx")
      );

      // 将生成的excel文件发送给客户端
      ctx.body = buffer;
    } catch (error) {
      return (ctx.body = fail([], error.message, CODE.BUSINESS_ERROR));
    }
  }
}

module.exports = {
  SystemPostController,
};
